package banner

import (
	"context"
	"github.com/gin-gonic/gin"
	"github.com/golang/protobuf/ptypes/empty"
	"go.uber.org/zap"
	"hosptial-record/api/base"
	"hosptial-record/forms"
	"hosptial-record/global"
	"hosptial-record/global/response"
	"hosptial-record/proto"
	"net/http"
)

// Create 创建轮播图
func Create(ctx *gin.Context) {
	var form forms.BannerForm
	if err := ctx.ShouldBind(&form); err != nil {
		base.HandleValidatorError(ctx, err)
		return
	}
	params := proto.BannerRequest{
		Index: form.Index,
		Image: form.Image,
		Url:   form.Url,
	}
	if res, err := global.GoodsSrvClient.CreateBanner(context.Background(), &params); err != nil {
		base.HandleGrpcErrorToHttp(err, ctx)
	} else {
		ctx.JSON(http.StatusOK, response.BaseResponse{
			Msg:  "创建成功",
			Data: res,
		})
	}
}

// Update 修改轮播图
func Update(ctx *gin.Context) {
	var form forms.UpdateBannerForm
	if err := ctx.ShouldBind(&form); err != nil {
		base.HandleValidatorError(ctx, err)
		return
	}
	// 填充数据
	params := proto.BannerRequest{
		Id:    form.ID,
		Index: form.Index,
		Image: form.Image,
		Url:   form.Url,
	}
	if _, err := global.GoodsSrvClient.UpdateBanner(ctx, &params); err != nil {
		base.HandleGrpcErrorToHttp(err, ctx)
	} else {
		ctx.JSON(http.StatusOK, response.BaseResponse{
			Msg: "修改成功",
		})
	}
}

// Delete 删除轮播图
func Delete(ctx *gin.Context) {
	id, err := base.GetID2Param(ctx)
	if err != nil {
		zap.S().Errorf("ID不合法")
		return
	}
	if _, err := global.GoodsSrvClient.DeleteBanner(context.Background(), &proto.BannerRequest{Id: id}); err != nil {
		base.HandleGrpcErrorToHttp(err, ctx)
		return
	} else {
		ctx.JSON(http.StatusOK, response.BaseResponse{
			Msg: "删除成功",
		})
	}
}

// List 轮播图列表
func List(ctx *gin.Context) {
	if res, err := global.GoodsSrvClient.BannerList(context.Background(), &empty.Empty{}); err != nil {
		base.HandleGrpcErrorToHttp(err, ctx)
		return
	} else {
		ctx.JSON(http.StatusOK, response.BaseResponse{
			Msg:  "获取成功",
			Data: res,
		})
	}
}
